package org.cms;

import java.io.*;
import java.nio.file.Path;
import java.util.Properties;

/**
 * Created by elnoa on 25/10/14.
 */
public class PropertiesHandler {

    private Properties properties;
    private String fileName;
//    private String jbossHome = System.getProperty("JBOSS_HOME");
    private String jbossHome = "/home/elnon/wildfly-8.1.0.Final/";

    public PropertiesHandler(String fileName) {
        this.fileName = fileName;
        this.properties = loadProperties();
    }

    /**
     * Load properties file of saved tokens
     *
     * @return
     */
    private Properties loadProperties() {
        Properties properties = new Properties();
        InputStream inputStream = null;

        try {

            inputStream = new FileInputStream(new File(jbossHome + fileName));
            properties.load(inputStream);

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return properties;
    }

    /**
     * save newly generated tokens in the property file
     */
    public void updateProperties() {

        Path propertyFile = null;
        OutputStream outputStream = null;
        try {

            outputStream = new FileOutputStream(new File(jbossHome + fileName));
            this.properties.store(outputStream, "updddated");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public java.util.Set<String> stringPropertyNames(){
        return properties.stringPropertyNames();
    }

    public String getProperty(String key) {
        return this.properties.getProperty(key);
    }

    public void setProperty(String refreshToken, String access_token) {
        this.properties.setProperty(refreshToken, access_token);
    }
}
